const fs = require("fs");
const db = require("../libs/DBHelper");

class CartController {

  getGoods(req, res) {
    let strGoods = fs.readFileSync("./data/goods.json");
    let dataGoods = JSON.parse(strGoods);

    res.json({
      msg: "查询成功",
      data: dataGoods
    })
  }
  getGoodsById(req, res) {
    let { id } = req.query;
    let strGoodsList = fs.readFileSync("./data/goodlist.json");
    let dataGoodsList = JSON.parse(strGoodsList);
    res.json({
      msg: "查询成功",
      data: dataGoodsList.find(item => item.id == id)
    })
  }

  // 加入购物车接口
  async add(req, res) {
    let { id, name, price, number, img, uId } = req.body;
    let sql_query = "SELECT * FROM `carts` WHERE `cStatus`=1 and `uId`=? and `pId`=?;"
    let params_query = [
      uId,//购买人
      id//pId 产品id
    ]

    let query_result = await db.exec(sql_query, params_query);
    let isAdd = query_result && query_result.length >= 1;//true 已购买
    if (isAdd) {
      let sql_update = "UPDATE carts SET `cNumber`=cNumber+?,`cTotal`=cNumber*`cPrice` WHERE  `cStatus`=1 AND `uId`=? AND`pId`=?;"
      let params_update = [
        number,
        uId, //购买人
        id //这个id就是pid 产品id
      ]
      let update_result = await db.exec(sql_update, params_update);
      let isUpdate = update_result && update_result.affectedRows;

      res.json({
        code: isUpdate ? 200 : -200,
        msg: isUpdate ? "加入购物车成功!u" : "加入购物车失败!u"
      })
    } else {
      //插入一条购买记录
      let sql_insert = "INSERT INTO carts(`pId`,`uId`,`cName`,`cPrice`,`cNumber`,`cTotal`,`cImg`)VALUES(?,?,?,?,?,?,?);"
      let params_insert = [
        id, uId, name, price, number, price * number, img
      ]

      let insert_results = await db.exec(sql_insert, params_insert);

      var isInsert = insert_results && insert_results.affectedRows;

      res.json({
        code: isInsert ? 200 : -200,
        msg: isInsert ? "加入购物车成功!i" : "加入购物车失败!"
      })
    }

  }

  async getCart(req, res) {
    let { uid } = req.query;
    let sql = "SELECT * FROM `carts`  WHERE `cStatus`=1 AND uId=?;";
    let params = [uid];
    let results = await db.exec(sql, params);
    res.json({
      msg: "查询成功",
      data: results
    })
  }

  async delete(req, res) {
    let { cId } = req.body;

    let sql = "UPDATE carts SET `cStatus`=0 WHERE `cId`=? ;";
    let params = [
      cId
    ]

    let results = await db.exec(sql, params);
    let isDel = results && results.affectedRows >= 1
    res.json({
      code: isDel ? 200 : -200,
      msg: isDel ? "删除成功" : "删除失败",
    })
  }

}

module.exports = new CartController;